package com.sxj.corejava.code13_jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author 石小俊
 */
public class Test11_批处理 {

    public static void main(String[] args) {
        test01();
        test02();
    }

    public static void test01() {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user(username,password,phone,address)")
                    .append(" values(?,?,?,?)")
                    .toString()
                    .toString();

            long begin = System.currentTimeMillis();

            for (int i = 0; i < 1000; i++) {
                ps = conn.prepareStatement(sql);
                ps.setString(1, "test" + i);
                ps.setString(2, "123456");
                ps.setString(3, "13812345678");
                ps.setString(4, "江苏-南京");
                ps.executeUpdate();
            }
            long end = System.currentTimeMillis();
            System.out.println("通过正常添加的方式添加1000条数据共耗费了" + (end - begin) + "毫秒");
        } catch (SQLException e) {
            throw new DataAccessException("数据访问异常");
        } finally {
            JDBCUtil.close(conn, ps, null);
        }
    }

    public static void test02() {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtil.getConnection();
            // 使用批处理必须存在事务
            conn.setAutoCommit(false);
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user(username,password,phone,address)")
                    .append(" values(?,?,?,?)")
                    .toString();

            long begin = System.currentTimeMillis();
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < 1000; i++) {
                ps.setString(1, "test" + i);
                ps.setString(2, "123456");
                ps.setString(3, "13812345678");
                ps.setString(4, "江苏-南京");
                // 将状态集对象添加到缓冲区
                ps.addBatch();
            }
            // 批量执行
            ps.executeBatch();
            conn.commit();
            long end = System.currentTimeMillis();
            System.out.println("通过批处理的方式添加1000条数据共耗费了" + (end - begin) + "毫秒");

        } catch (SQLException e) {
            throw new DataAccessException("数据访问异常");
        } finally {
            JDBCUtil.close(conn, ps, null);
        }
    }

}
